#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/TcpClient.h>
#include <muduo/net/TcpConnection.h>
#include <iostream>
#include <string>
#include <memory>
#include <functional>
#include <muduo/base/CountDownLatch.h>


class TranslateClient{
public:

    TranslateClient(const std::string& serverip,uint16_t serverport):_client(_loopthread.startLoop(),muduo::net::InetAddress(serverip,serverport),"TranslateClient"),_latch(1){

        auto func1 = std::bind(&TranslateClient::onConnection,this,std::placeholders::_1);
        
        //设置连接成功后的回调函数
        _client.setConnectionCallback(func1);
        
        auto func2 = std::bind(&TranslateClient::onMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3);
        //设置连接成功后的回调函数
        std::cout << 1 << std::endl;
        
        _client.setMessageCallback(func2);

    }

    void connection()//clinet的连接
    {

        _client.connect();//进行连接服务器，会立即返回

        _latch.wait();//阻塞等待直到连接建立成功
    }

    bool send(const std::string& msg)
    {
        if(_conn->connected())
        {
            _conn->send(msg);
            return true;
        }
        return false;
    }


private:


    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())//因为是异步的，可能断开连接，所以需要：判断该连接是否存在，防止出错
        {
            _latch.countDown();//连接成功唤醒主线程中的阻塞
            _conn = conn;
        }
        else{
            _conn.reset();
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr& _conn,muduo::net::Buffer* buf,muduo::Timestamp timeout)
    {
        std::cout << "翻译结果：" << buf->retrieveAllAsString() << std::endl;
    }

private:
    muduo::net::EventLoopThread _loopthread;//不在像中服务器使用eventloop，因为他是阻塞式的循环，这样会导致无法send
    muduo::CountDownLatch _latch;
    muduo::net::TcpConnectionPtr _conn;
    muduo::net::TcpClient _client;
};


int main()
{
    TranslateClient client("127.0.0.1",8081);
    std::cout << 1 << std::endl;
    
    client.connection();
    while(1)
    {
        std::string buf;
        std::cin >> buf;

        client.send(buf);
    }


    return 0;
}

